using Cysharp.Threading.Tasks;
using MoonFramework.FSM;
using Tool;
using UnityEngine;

namespace Entity.Player.State
{
    public class PlayerRunState : RunState
    {
        protected override async UniTaskVoid Run()
        {
            while (_isRun)
            {
                await UniTask.Yield();
                // 获取虚拟相机的旋转角度（Y轴）
                var y = InputManager.Instance.MainCamera.transform.rotation.eulerAngles.y;

                // 计算目标方向（相对于虚拟相机）
                _actor.viewController.targetDir = new Vector3(((Player)_actor).hor, 0, ((Player)_actor).ver).normalized; // 正常化输入方向
                if (_actor.viewController.targetDir.sqrMagnitude > 0.01f)
                {
                    _actor.viewController.targetDir = Quaternion.Euler(0, y, 0) * _actor.viewController.targetDir;
                }
                else
                {
                    _actor.viewController.targetDir = InputManager.Instance.MainCamera.transform.forward;
                    _actor.viewController.targetDir.y = 0; // 只考虑水平方向
                }
                ((PlayerFsm)fsmMachine).Move(_actor.viewController.targetDir, _actor.RunSpeed);
                ((PlayerFsm)fsmMachine).Turn(_actor.viewController.targetDir, _actor.RotationSpeed);
            }
        }

        protected override void FootStep()
        {
            index %= 2;
            _actor.viewController.PlayAudio(index == 0? PlayerAudioName.LeftLeg : 
                    PlayerAudioName.RightLeg, 
                0.25f);
            index++;
        }
    }
}